package com.heima.search.listener;

import com.alibaba.fastjson.JSON;
import com.heima.common.constants.ArticleConstants;

import com.heima.model.search.vos.SearchArticleVo;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.io.IOException;


/**
 * @Author: JW
 * @Description: TODO 监听消息
 * @DateTime: 2022-02-18 11:40
 **/
@Component
public class SyncArticleListener {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * @Author: JW
     * @Description:  TODO 监听app对文章的修改和增加
     * @Date: 11:42 2022-02-18
     * @Param: []
     * @return: void
    **/
    @KafkaListener(topics = ArticleConstants.ARTICLE_ES_SYNC_TOPIC)
    public void upDateOrSaveArticle(String message){

        if (message == null){
            return;
        }

        //解析结果
        SearchArticleVo searchArticleVo = JSON.parseObject(message, SearchArticleVo.class);

        IndexRequest indexRequest = new IndexRequest("app_info_article").id(searchArticleVo.getId().toString());

        indexRequest.source(message, XContentType.JSON);
        try {
            //新增文档
            restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
